// pages/upload/upload-edit.js
const { uploadAPI, videoUploadAPI } = require('../../interface.js');

Page({
  data: {
    selectedVideo: null, // 选中的视频信息
    selectedCover: null, // 选中的封面图信息
    videoTitle: '', // 视频标题
    videoDescription: '', // 视频描述
    uploadedVideoFileId: null, // 上传后的视频文件ID
    uploadedCoverFileId: null, // 上传后的封面文件ID
    isUploading: false, // 是否正在上传
    canPublish: false, // 是否可以发布
    videoDurationText: '', // 视频时长文本
    videoSizeText: '', // 视频大小文本
    uploadProgress: '准备上传...' // 上传进度文本
  },

  onLoad: function (options) {
    // 从全局数据获取视频信息
    const app = getApp();
    if (app.globalData.selectedVideo) {
      this.setData({
        selectedVideo: app.globalData.selectedVideo
      });
      this.updateVideoInfo();
      this.checkCanPublish(); // 初始化按钮状态
    } else {
      // 如果没有视频信息，返回上一页
      wx.showToast({
        title: '请先选择视频',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 更新视频信息显示
  updateVideoInfo: function() {
    const video = this.data.selectedVideo;
    if (!video) return;

    // 格式化时长
    const duration = Math.floor(video.duration);
    const minutes = Math.floor(duration / 60);
    const seconds = duration % 60;
    const durationText = `${minutes}:${seconds.toString().padStart(2, '0')}`;

    // 格式化文件大小
    const size = video.size;
    let sizeText = '';
    if (size < 1024 * 1024) {
      sizeText = `${(size / 1024).toFixed(1)}KB`;
    } else {
      sizeText = `${(size / (1024 * 1024)).toFixed(1)}MB`;
    }

    this.setData({
      videoDurationText: durationText,
      videoSizeText: sizeText
    });

    this.checkCanPublish();
  },

  // 检查是否可以发布
  checkCanPublish: function() {
    const canPublish = this.data.videoTitle.trim().length > 0 && 
                      this.data.selectedVideo && 
                      this.data.selectedCover;
    this.setData({ canPublish });
  },



  // 选择自定义封面图片
  chooseCoverImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          selectedCover: {
            tempFilePath: tempFilePath
          }
        });
        this.checkCanPublish(); // 更新发布按钮状态
        wx.showToast({
          title: '封面选择成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.log('选择封面失败:', err);
        wx.showToast({
          title: '选择失败',
          icon: 'error'
        });
      }
    });
  },

  // 标题输入
  onTitleInput: function(e) {
    this.setData({
      videoTitle: e.detail.value
    });
    this.checkCanPublish();
  },

  // 描述输入
  onDescriptionInput: function(e) {
    this.setData({
      videoDescription: e.detail.value
    });
  },

  // 上传文件
  uploadFile: function(filePath, fileType = 'video') {
    return new Promise((resolve, reject) => {
      const uploadTask = wx.uploadFile({
        url: `${require('../../interface.js').BASE_URL}/api/miniprogram/upload/file`,
        filePath: filePath,
        name: 'file',
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              resolve(data.data.file_id)
            } else {
              reject(new Error(data.msg || '上传失败'))
            }
          } catch (e) {
            reject(new Error('上传响应解析失败'))
          }
        },
        fail: (error) => {
          reject(error)
        }
      })
      
      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        const progress = Math.round(res.progress)
        const progressText = fileType === 'video' ? `正在上传视频 ${progress}%` : `正在上传封面 ${progress}%`
        this.setData({
          uploadProgress: progressText
        })
      })
    });
  },

  // 发布视频
  publishVideo: function() {
    if (!this.data.canPublish || this.data.isUploading) {
      return;
    }

    this.setData({ 
      isUploading: true,
      uploadProgress: '开始上传...'
    });

    // 先上传视频文件
    this.setData({ uploadProgress: '正在上传视频文件...' });
    this.uploadFile(this.data.selectedVideo.tempFilePath, 'videos')
      .then(videoFileId => {
        this.setData({ uploadedVideoFileId: videoFileId });
        
        // 上传封面图片（必选）
        this.setData({ uploadProgress: '正在上传封面图片...' });
        return this.uploadFile(this.data.selectedCover.tempFilePath, 'covers');
      })
      .then(coverFileId => {
        this.setData({ uploadedCoverFileId: coverFileId });
        
        // 调用视频发布接口
        this.setData({ uploadProgress: '正在发布视频...' });
        return videoUploadAPI.uploadVideo(
          this.data.videoTitle,
          this.data.videoDescription,
          this.data.uploadedVideoFileId,
          this.data.uploadedCoverFileId
        );
      })
      .then(res => {
        this.setData({ isUploading: false });
        
        if (res.code === 200) {
          this.setData({ uploadProgress: '发布成功！' });
          wx.showToast({
            title: '发布成功',
            icon: 'success'
          });
          
          // 清除全局数据
          const app = getApp();
          app.globalData.selectedVideo = null;
          
          // 返回到视频列表页面
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/video/video'
            });
          }, 1500);
        } else {
          throw new Error(res.msg || '发布失败');
        }
      })
      .catch(err => {
        this.setData({ 
          isUploading: false,
          uploadProgress: '准备上传...'
        });
        console.error('发布视频失败:', err);
        wx.showToast({
          title: err.message || '发布失败',
          icon: 'error'
        });
      });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
});